import { useSize } from 'ahooks';
import { createStyles } from 'antd-style';
import { useEffect, useRef, useState } from 'react';

function getRectHeightContainMargin(dom: HTMLElement) {
  const style = window.getComputedStyle(dom);
  return dom.clientHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
}

const useStyle = createStyles(({ prefixCls }) => {
  return {
    rewrite: {
      [`.${prefixCls}-table-body  table:has(.${prefixCls}-table-placeholder)`]: {
        minHeight: '100%',
      },
      [`.${prefixCls}-table-empty .${prefixCls}-table-body table`]: {
        minHeight: '100%',
      },
    },
  };
});

export function useYmTableScrollY() {
  // 内部用来控制滚动高度用的,不允许用户设置
  const [scrollY, setScrollY] = useState<number>(400);
  // 表格的ref dom
  const tableRef = useRef<HTMLDivElement>(null);

  // 计算表格高度的
  const size = useSize(tableRef);
  const cSize = useSize(tableRef.current?.getElementsByClassName('ant-spin-container')?.[0]);

  // 计算表格body区域的实际高度
  useEffect(() => {
    const divH = size?.height;
    let otherH = 0;
    // 表头的外层dom
    const headerDom = tableRef.current?.getElementsByClassName('ant-table-thead')[0] as HTMLDivElement | undefined;
    // 分页dom
    const pagination = tableRef.current?.getElementsByClassName('ant-table-pagination')?.[0] as
      | HTMLDivElement
      | undefined;

    if (headerDom) {
      otherH += getRectHeightContainMargin(headerDom);
    }
    if (pagination) {
      otherH += getRectHeightContainMargin(pagination);
    }
    if (divH) {
      const tableDom = tableRef.current?.getElementsByClassName('ant-table')[0] as HTMLDivElement | undefined;
      const tbodyDom = tableDom?.getElementsByClassName('ant-table-body')[0] as HTMLDivElement | undefined;

      if (tableDom && tbodyDom) {
        tbodyDom.style.height = divH - otherH + 'px';
        tbodyDom.style.overflow = 'auto auto';
        setScrollY(divH - otherH);
      }
    }
  }, [size?.height, cSize?.height]);

  const cssStyle = useStyle();

  return {
    tableRef,
    scrollY,
    className: (str?: string) => cssStyle.cx(str, cssStyle.styles.rewrite),
  };
}
